﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GeneratorLib.DB;
using GeneratorLib.DB.Connectios;
using GeneratorLib.DB.Schemas;
using DBExplorer.CusEventArgs;
using UIShell.OSGi;
using Pasys.PresentationCore;

namespace DBExplorer.Generators
{
    public partial class TableFieldList : Form, GeneratorLib.IGenerator
    {
        //private
        private ICommandBusService commandBus;

        public IConnection Connection { get; set; }
        private TableInfo _table;
        public TableInfo Table
        {
            get
            {
                return _table;
            }
            set
            {
                _table = value;
                if (value != null)
                {
                    this.Text =string.Format("{0}", value.TableName);
                }
            }
        }

        public void AddToolStripItem(ToolStripItem item)
        {

        }


        public TableFieldList()
        {
            InitializeComponent();
            commandBus = BundleRuntime.Instance.GetFirstOrDefaultService<ICommandBusService>();
            this.Text = "Table Infomation";
        }

        public override int GetHashCode()
        {
            return string.Format("{0}{1}", this.Connection.ConnectStr, this.Table).GetHashCode();
        }

        public override bool Equals(object obj)
        {
            TableFieldList obj2 = obj as TableFieldList;
            if (obj2 == null)
            {
                return false;
            }

            return obj2.Connection.ConnectStr.Equals(this.Connection.ConnectStr) && obj2.Table.TableName.Equals(this.Table.TableName);
        }


        //private void AddToolItems()
        //{
        //    ToolStripMenuItem item0 = new ToolStripMenuItem("Refresh");
        //    item0.Tag = 0;
        //    ToolStripMenuItem item1 = new ToolStripMenuItem("Add Relationship");
        //    item1.Tag = 1;
        //    ToolStripMenuItem item2 = new ToolStripMenuItem("Display Information");
        //    item2.Tag = 2;

        //    this.AddToolStripItem(item0);
        //    this.AddToolStripItem(item1);
        //    this.AddToolStripItem(item2);
        //}

        #region IGenerator
        public void Generate()
        {
        }

        public void Generate(string command)
        {
        }

        public void RefreshContent()
        {
            refreshTable();
            showRelations();
        }

        public void Save()
        {
        }

        public bool CanSave()
        {
            return false;
        }
        public bool CanGenerate()
        {
            return false;
        }
        #endregion

        /*
        public override void Generate(ToolStripItem item)
        {
            base.Generate(item);
            switch (Convert.ToInt32(item.Tag))
            {
                case 0:
                    refreshTable();
                    showRelations();
                    break;
                case 1:
                    showRelationDialog();
                    //if (ShowEditRelationClickedHandler != null)
                    //{
                    //    TableSelectedEventArg arg = new TableSelectedEventArg(this.Table);
                    //    ShowEditRelationClickedHandler(this, arg);
                    //    if (arg.Result)
                    //    {
                    //        showRelations();
                    //    }
                    //}
                    break;
                case 2:
                    if (ShowEditTableInfomationClickedHandler != null)
                    {
                        TableSelectedEventArg arg=  new TableSelectedEventArg(this.Table);
                        ShowEditTableInfomationClickedHandler(this,arg);
                        if (arg.Result)
                        {
                            refreshTable();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        */
        private void refreshTable()
        {
            lsvTableField.Items.Clear();
            //this.Table = MYSQLUtility.GetTableInfo(this.Connection, this.Table.TableName);

            TableInfoAddin tableAddin = this.Connection.FindTableAddin(this.Table.TableName);

            if (tableAddin.TableDisplayName.Trim().Length > 0)
            {
                this.Text = string.Format("{0}({1})", tableAddin.TableDisplayName, this.Table.TableName);
            }

            foreach (FieldInfo field in Table.Fields)
            {
                ListViewItem item = lsvTableField.Items.Add(field.FieldName);

                FieldInfoAddin fieldAddin = tableAddin.FindFieldAddin(field.FieldName, field.Comment);
                if (fieldAddin != null)
                {
                    item.SubItems.Add(string.Format("{0}", fieldAddin.DisplayName));
                }
                else
                {
                    item.SubItems.Add(string.Format("{0}", field.Comment));
                }

                item.SubItems.Add(string.Format("{0}", field.FieldType));
                item.SubItems.Add(string.Format("{0}", field.FieldSize));

                item.SubItems.Add(string.Format("{0}", (field.Key == true ? "YES" : "")));
                item.SubItems.Add(string.Format("{0}", (field.Nullabled == true ? "YES" : "")));
                item.SubItems.Add(string.Format("{0}", field.DefaultValue));

                item.SubItems.Add(string.Format("{0}", (tableAddin.IsListField(field.FieldName) == true ? GlobalValues.CheckBoxStr_Checked : "")));
                item.SubItems.Add(string.Format("{0}", (tableAddin.IsSearchField(field.FieldName) == true ? GlobalValues.CheckBoxStr_Checked : "")));

            }
        }

        private void lsvTableField_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            TableInfoAddin tableAddin = this.Connection.FindTableAddin(this.Table.TableName);

            ListViewHitTestInfo testInfo = lsvTableField.HitTest(e.X, e.Y);
            if (testInfo.SubItem != null)
            {
                int index = testInfo.Item.SubItems.IndexOf(testInfo.SubItem);
                if (index == 7)
                {
                    if (testInfo.SubItem.Text.Length == 0)
                    {
                        testInfo.SubItem.Text = GlobalValues.CheckBoxStr_Checked;
                        tableAddin.AddListField(testInfo.Item.Text);
                    }
                    else
                    {
                        testInfo.SubItem.Text = "";
                        tableAddin.RemoveListField(testInfo.Item.Text);
                    }
                }
                else if (index == 8)
                {
                    if (testInfo.SubItem.Text.Length == 0)
                    {
                        testInfo.SubItem.Text = GlobalValues.CheckBoxStr_Checked;
                        tableAddin.AddSearchField(testInfo.Item.Text);
                    }
                    else
                    {
                        testInfo.SubItem.Text = "";
                        tableAddin.RemoveSearchField(testInfo.Item.Text);
                    }
                }
                if (TableAddinChangedHandler != null)
                    TableAddinChangedHandler(this, EventArgs.Empty);
            }
        }

        private void showRelationDialog()
        {
            TableSelectedEventArg arg = new TableSelectedEventArg(this.Table);
            ShowEditRelationFrm(arg);
            if (arg.Result)
            {
                showRelations();
            }
        }

        private void ShowEditRelationFrm(TableSelectedEventArg arg)
        {
            FrmDBRelationEdit edit = new FrmDBRelationEdit();
            if (arg.Field != null)
            {
                edit.Field = arg.Field;
            }
            else
            {
                edit.Table = arg.Table;
            }

            DialogResult res = edit.ShowDialog();
            if (res != DialogResult.OK)
                return;

            IConnection con = arg.Table.Connection;
            Relation r = edit.RelationShip;
            try
            {
                con.AddRelation(r);
                var explorerMng = (DBExplorerManager)BundleRuntime.Instance.GetFirstOrDefaultService<IDBExplorerManager>();
                explorerMng.ConnectionInfos.Save();
                arg.Result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void showRelations()
        {
            var res = from s in this.Connection.Relations
                      where
                          s != null && (
                          s.PrimaryTable.TableName.ToLower().CompareTo(this.Table.TableName.ToLower()) == 0 ||
                          s.ForeignTable.TableName.ToLower().CompareTo(this.Table.TableName.ToLower()) == 0)
                      select s;

            lstRelation.Items.Clear();
            txtRelation.Clear();
            foreach (var r in res)
            {
                lstRelation.Items.Add(r);
            }

        }

        private void lstRelation_SelectedIndexChanged(object sender, EventArgs e)
        {
            Relation r = (Relation)lstRelation.SelectedItem;
            if (r != null)
            {
                txtRelation.Text = r.GetDiscription();
            }
            else
            {
                txtRelation.Clear();
            }
        }

        public event EventHandler TableAddinChangedHandler;

        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Relation r = lstRelation.SelectedItem as Relation;
            if (r != null)
            {
                this.Table.Connection.RemoveRelation(r);
                showRelations();
            }
        }

        private void lstRelation_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right) return;
            cmRelations.Show(lstRelation, e.X, e.Y);
        }

        private void cmAllInList_Click(object sender, EventArgs e)
        {
            TableInfoAddin tableAddin = this.Connection.FindTableAddin(this.Table.TableName);
            foreach (var field in this.Table.Fields)
            {
                tableAddin.AddListField(field.FieldName);
            }
            if (TableAddinChangedHandler != null)
                TableAddinChangedHandler(this, EventArgs.Empty);

            refreshTable();
        }

        private void cmAllOutList_Click(object sender, EventArgs e)
        {
            TableInfoAddin tableAddin = this.Connection.FindTableAddin(this.Table.TableName);
            foreach (var field in this.Table.Fields)
            {
                tableAddin.RemoveListField(field.FieldName);
            }
            if (TableAddinChangedHandler != null)
                TableAddinChangedHandler(this, EventArgs.Empty);
            refreshTable();
        }

        private void cmAllInSearch_Click(object sender, EventArgs e)
        {
            TableInfoAddin tableAddin = this.Connection.FindTableAddin(this.Table.TableName);
            foreach (var field in this.Table.Fields)
            {
                tableAddin.AddSearchField(field.FieldName);
            }
            if (TableAddinChangedHandler != null)
                TableAddinChangedHandler(this, EventArgs.Empty);
            refreshTable();
        }

        private void cmAllOutSearch_Click(object sender, EventArgs e)
        {
            TableInfoAddin tableAddin = this.Connection.FindTableAddin(this.Table.TableName);
            foreach (var field in this.Table.Fields)
            {
                tableAddin.RemoveSearchField(field.FieldName);
            }
            if (TableAddinChangedHandler != null)
                TableAddinChangedHandler(this, EventArgs.Empty);
            refreshTable();
        }

        private void lsvTableField_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right) return;
            cmTableFields.Show(lsvTableField, e.X, e.Y);
        }

        private void cmAddRelationShip_Click(object sender, EventArgs e)
        {
            showRelationDialog();
        }

        private void TableFieldList_Load(object sender, EventArgs e)
        {
            refreshTable();
            showRelations();
        }

        private void TableFieldList_Activated(object sender, EventArgs e)
        {
            Console.WriteLine("TableFieldList_Activated");
        }

        private void TableFieldList_Deactivate(object sender, EventArgs e)
        {
            Console.WriteLine("TableFieldList_Deactivate");
        }

        private void displayInfomationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            {
                TableSelectedEventArg arg = new TableSelectedEventArg(this.Table);
                ShowEditTableInfomationFrm(arg);
                if (arg.Result)
                {
                    refreshTable();
                }
            }
        }

        private void ShowEditTableInfomationFrm(TableSelectedEventArg arg)
        {
            FrmTableAddinEdit edit = new FrmTableAddinEdit();
            TableInfoAddin tableAddin = arg.Table.Connection.FindTableAddin(arg.Table.TableName);
            edit.TableAddin = tableAddin;
            DialogResult res = edit.ShowDialog(this);
            if (res != DialogResult.OK) return;

            try
            {
                var explorerMng = (DBExplorerManager)BundleRuntime.Instance.GetFirstOrDefaultService<IDBExplorerManager>();
                explorerMng.ConnectionInfos.Save();
                arg.Result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }




    }

}
